package com.cowain.service.impl;

import com.cowain.api.commons.SystemUtils;
import com.cowain.api.constant.Constant;
import com.cowain.entity.UserEntity;
import com.cowain.info.UserInfo;
import com.cowain.respository.UserRepository;
import com.cowain.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author fxw
 * @Date 2022/5/12 20:45
 */
@Service
public class UserServiceImpl implements UserService {
    final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean addUser(UserEntity userInfo) {
        UserInfo entity = userRepository.save(convert(userInfo));
        if (!SystemUtils.isNULL(entity) && entity.getUid() != Constant.ZERO) {
            return true;
        }
        return false;
    }

    /**
     * 删除一条或者删除多条的数据
     *
     * @param uid
     * @return
     */
    @Override
    public boolean delUser(String uid) {
        if (!uid.contains("_")) {
            //更新一条
            try {
                //先查询在更新
                logger.info("System User Select User ByUid start");
                UserInfo userInfo = userRepository.findById(Long.parseLong(uid)).get();
                logger.info("System User update User ByUid start");
                userInfo.setUstatus(1);
                userRepository.save(userInfo);
                logger.info("System User update User ByUid successful");
                return true;
            } catch (Exception e) {
                logger.error("System User update User ByUid fail");
                return false;
            }
        } else {
            try {
                //删除多条
                String[] uids = uid.split("_");
                Set<Long> list = new HashSet<>();
                for (String id : uids) {
                    list.add(Long.parseLong(id));
                }
                userRepository.updates(list);
                logger.info("System User update User ByBatchUid successful");
                return true;
            } catch (NumberFormatException e) {
                logger.error("System User update User ByBatchUid fail");
                return false;
            }
        }
    }

    @Override
    public boolean updateUser(UserEntity userEntity) {
        UserInfo userInfo = userRepository.findById(userEntity.getUid()).get();
        if (!SystemUtils.isNULLEmpty(userEntity.getUname())) {
            userInfo.setUname(userEntity.getUname());
        }
        if (!SystemUtils.isNULLEmpty(userEntity.getUmail())) {
            userInfo.setUname(userEntity.getUmail());
        }
        if (!SystemUtils.isNULLEmpty(userEntity.getUphone())) {
            userInfo.setUname(userEntity.getUphone());
        }
        UserInfo save = userRepository.save(userInfo);
        return true;
    }

    @Override
    public List<UserEntity> findAll() {
        List<UserInfo> userInfo = userRepository.findAll();
        return convertList(userInfo);
    }

    public List<UserEntity> findAllByWhere(UserEntity userEntity) {
        UserInfo userInfo = convert(userEntity);
        ExampleMatcher uphone = ExampleMatcher.matching().withMatcher("uphone"
                        , m -> m.contains())
                .withIgnorePaths("uid")
                .withIgnorePaths("ustatus");
        Example example = Example.of(userInfo, uphone);
        List<UserInfo> userInfos = userRepository.findAll(example);
        return convertList(userInfos);
    }
    public  List<UserEntity> findUserByTime(String t1,String t2){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        List<UserInfo> users = null;
        try {
            users = userRepository.findAllByUtimeBetween(sdf.parse(t1),sdf.parse(t2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  convertList(users);
    }
    private UserInfo convert(UserEntity userEntity) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userEntity, userInfo);
        userEntity.setStartTime(new Date());
        userInfo.setuTime(userEntity.getStartTime());
        return userInfo;
    }

    private List<UserEntity> convertList(List<UserInfo> userInfo) {
        List<UserEntity> list = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        for (UserInfo info : userInfo) {
            BeanUtils.copyProperties(info, userEntity);
            list.add(userEntity);
        }
        return list;
    }
    public Map<String,Object> queryUsers(UserEntity userEntity){

        //分页的对象 排序
        //默认的分页规则;
        Pageable of = PageRequest.of(userEntity.getCurrentPage(), userEntity.getPageSize());

        //如果需要排序,按照指定字段排序;
        if(!SystemUtils.isNULLEmpty(userEntity.getSort())){
            String[] sorts = null;
            sorts = userEntity.getSort().split(",");

            if("ASC".equals(userEntity.getSortType())){
                of = PageRequest.of(userEntity.getCurrentPage(), userEntity.getPageSize(), Sort.Direction.ASC,sorts);
            }else{
                of = PageRequest.of(userEntity.getCurrentPage(), userEntity.getPageSize(), Sort.Direction.DESC,sorts);
            }
        }

        //条件查询
        Specification<UserInfo> spec = new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

                //自定义条件的对象
                Predicate predicate = cb.conjunction();

                //根据邮箱查询
                if(!SystemUtils.isNULLEmpty(userEntity.getUmail())){
                    predicate.getExpressions().add(cb.equal(root.get("umail"),userEntity.getUmail()));
                }

                //根据手机是否模糊匹配查询
                if(!SystemUtils.isNULLEmpty(userEntity.getUphone())){
                    predicate.getExpressions().add(cb.like(root.get("uphone").as(String.class),"%"+userEntity.getUphone()+"%"));
                }

                //起始时间
                if(!SystemUtils.isNULLEmpty(userEntity.getStartTime().toString())){
                    predicate.getExpressions().add(
                            cb.greaterThanOrEqualTo(root.get("utime").as(String.class),userEntity.getStartTime().toString())
                    );
                }

                //终止时间
                if(!SystemUtils.isNULLEmpty(userEntity.getEndTime().toString())){
                    predicate.getExpressions().add(
                            cb.lessThanOrEqualTo(root.get("utime").as(String.class),userEntity.getEndTime().toString())
                    );
                }

                return predicate;
            }
        };

        //根据指定的分页和条件查询规则查询当前页内容
        Page<UserInfo> page = userRepository.findAll(spec,of);

        //定义我们的数据库查询出来的数据
        List<UserInfo> content = page.getContent();
        //转成我们前端使用的对象;
        List<UserEntity> users = convertList(content);

        //通过页内容,构建数据
        Map<String,Object> map = new HashMap<>();
        map.put("users",users); //查询到的列表信息
        map.put("totalPage",page.getTotalPages());//总页数
        map.put("currentPage",userEntity.getCurrentPage());
        map.put("pageSize",userEntity.getPageSize());

        return map;
    }
}
